package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 处理文件上传下载
 */
@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {
    //读取yml文件中的配置
    @Value("${reggie.path}")
    private String path;

    @PostMapping("upload")
    public R upLoad(MultipartFile file) throws IOException {
        log.info(file.toString());
        //创建一个目录对象
        File dirFile = new File(path);
        //判断文件夹是否存在，如果不存在就创建
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //使用uuid重新生成文件名
        String uuid = UUID.randomUUID().toString();
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uuidFileName = uuid + s;
        //将文件存到指定的位置
        file.transferTo(new File(path+"/"+uuidFileName));
        return R.success(uuidFileName);
    }
    //文件下载
    @GetMapping("download")
    public R download(String name, HttpServletResponse response) throws IOException {
        //先读
        FileInputStream fis = new FileInputStream(path +"/"+ name);
        //在写
        ServletOutputStream os = response.getOutputStream();
        //然后下载
        IOUtils.copy(fis,os);
        fis.close();
        return R.success("下载成功");
    }
}
